package cetcbigdata.da.service.guangdong.util;

import cetcbigdata.da.base.DownloadAndUploadMinio;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @author YuanGongPing
 * @version 0.1
 * @description GdUtil
 * @since 2022/8/25 11:07
 */


public class GdUtil {
    public static JSONObject getBaseInfo(String html) {
        JSONObject base = new JSONObject();

        JSONObject response = JSONObject.parseObject(html);
        JSONObject basicInfoex = response.getJSONObject("AUDIT_ITEM_EXTEND");
        JSONArray ywCode = response.getJSONArray("AUDIT_ITEM_COUNTRY_CODE");

        //基础信息
        JSONObject baseInfo = new JSONObject();
        JSONObject basicInfo = response.getJSONObject("AUDIT_ITEM");
        if(ywCode.isEmpty()){
            baseInfo.put("业务办理项编码","无");
        }else {
            for (Object o : ywCode) {
                JSONObject ywcode = (JSONObject) o;
                baseInfo.put("业务办理项编码",
                        isNotBlankOrNull(basicInfo.getString("YW_CODE")) ? ywcode.getString("YWCODE_G") : "无");
            }
        }

        baseInfo.put("事项名称", basicInfo.getString("CATANAME"));
        baseInfo.put("事项名称短语", isNotBlankOrNull(basicInfoex.getString("SORTITEMNAME")) ?
                basicInfoex.getString("SORTITEMNAME") : "无");
        baseInfo.put("事项类型", basicInfo.getString("TASK_TYPE_TEXT"));
        baseInfo.put("承诺办结时限", basicInfo.getInteger("PROMISE_DAY") +
                basicInfo.getString("ANTICIPATE_TYPE_TEXT"));
        baseInfo.put("办件类型", basicInfo.getString("PROJECT_TYPE_TEXT"));
        baseInfo.put("法定办结时限", basicInfo.getInteger("ANTICIPATE_DAY") +
                basicInfo.getString("ANTICIPATE_TYPE_TEXT"));
        baseInfo.put("实施编码", basicInfo.getString("NATION_TASK_CODE"));
        baseInfo.put("办理形式", basicInfo.getString("HANDLE_TYPE_TEXT"));
        baseInfo.put("基本编码", basicInfo.getString("NATION_CATALOG_CODE"));
        baseInfo.put("事项版本", basicInfo.getInteger("TASK_VERSION"));
        baseInfo.put("实施主体性质", basicInfo.getString("DEPT_TYPE"));
        baseInfo.put("实施主体编码", basicInfo.getString("TONGYI_CODE"));
        baseInfo.put("网办深度", basicInfo.getString("WBSD_LEVEL_TEXT"));
        baseInfo.put("到办事现场次数", basicInfoex.getInteger("LIMIT_SCENE_NUM"));
        baseInfo.put("必须现场办理原因", isNotBlankOrNull(basicInfoex.getString("SCBLSM")) ?
                basicInfoex.getString("SCBLSM") : "无");
        baseInfo.put("是否告知承诺制",
                isNotBlankOrNull(basicInfoex.getString("IS_NOTIFY_PROMISE")) ? (basicInfoex.getString("IS_NOTIFY_PROMISE").equals("1") ? "是" : "否") : "无");
        baseInfo.put("是否进驻政务大厅",
                isNotBlankOrNull(basicInfoex.getString("IS_ENTRY_CENTER").equals("1") ? "是" : "否") ? (basicInfoex.getString("IS_ENTRY_CENTER").equals("1") ? "是" : "否") : "无");
        baseInfo.put("是否支持物流快递", basicInfoex.getString("IS_EXPRESS_TEXT"));
        baseInfo.put("是否支持预约办理", basicInfoex.getString("IS_SCHEDULE_TEXT"));
        baseInfo.put("在线预约地址",
                isNotBlankOrNull(basicInfoex.getString("APPOINTMENT_URL")) ?
                        basicInfoex.getString("APPOINTMENT_URL") : "无");
        baseInfo.put("联办机构",
                isNotBlankOrNull(basicInfoex.getString("OTHER_DEPT")) ?
                        basicInfoex.getString("OTHER_DEPT") : "无");
        baseInfo.put("委托部门",
                isNotBlankOrNull(basicInfo.getString("ENTRUST_NAME")) ?
                        basicInfo.getString("ENTRUST_NAME") : "无");

        String daptUrl = String.format("https://www.gdzwfw.gov.cn/portal/branch-hall?orgCode=%s",
                response.getJSONObject("AUDIT_ITEM").getString("DEPT_CODE"));
        baseInfo.put("实施主体", response.getJSONObject("AUDIT_ITEM").getString("DEPT_NAME") + "," + daptUrl);
        base.put("基础信息", baseInfo);

        //审批信息
        JSONObject ApprovalInfo = new JSONObject();
        ApprovalInfo.put("行使层级", basicInfo.getString("USE_LEVEL_TEXT"));
        ApprovalInfo.put("权力来源", basicInfo.getString("ITEMSOURCE"));
        ApprovalInfo.put("审批服务形式", basicInfoex.getString("SERVICE_TYPE_TEXT"));
        ApprovalInfo.put("业务系统", basicInfoex.getString("XTMC"));
        base.put("审批信息", ApprovalInfo);


        //审批结果
        List<JSONObject> approvalResult = new ArrayList<>();
        JSONArray isRelateLicense = response.getJSONArray("AUDIT_ITEM_RESULT");
        for (int i = 0; i < isRelateLicense.size(); i++) {
            JSONObject jo1 = isRelateLicense.getJSONObject(i);
            JSONObject items = new JSONObject();
            items.put("名称", jo1.getString("NAME"));
            items.put("类型", jo1.getString("SUBJECT_RESULT_TYPE_TEXT"));
            JSONArray EMPTYATTACHLIST = jo1.getJSONArray("EMPTYATTACHLIST");
            JSONArray RESULTATTACHLIST = jo1.getJSONArray("RESULTATTACHLIST");
            items.put("关联状态",
                    jo1.getInteger("ISRELATELICENSE").equals(0) ? "无电子证照" :
                            jo1.getInteger("ISRELATELICENSE").equals(1) ? "已关联电子证照" : null);
            for (int j = 0; j < EMPTYATTACHLIST.size(); j++) {
                JSONObject jo2 = EMPTYATTACHLIST.getJSONObject(j);
                String fileUrl = String.format("https:%s", jo2.getString("FILEPATH"));
                JSONObject template = new JSONObject();
                template.put("名称", jo2.getString("ATTACHNAME"));
                template.put("源地址", fileUrl);
                template.put("minioId", fileDownloadAndUploadMinioGet(fileUrl, jo2.getString("ATTACHNAME")));
                items.put("模板", template);
            }
            for (int c = 0; c < RESULTATTACHLIST.size(); c++) {
                JSONObject jo3 = RESULTATTACHLIST.getJSONObject(c);
                JSONObject template1 = new JSONObject();
                String filUrl1 = String.format("https:%s",
                        jo3.getString("FILEPATH"));
                template1.put("名称",jo3.getString("ATTACHNAME" ));
                template1.put("源地址", filUrl1);
                template1.put("minioId", fileDownloadAndUploadMinioGet(filUrl1, jo3.getString("ATTACHNAME" )));
                items.put("样例", template1);
            }
            approvalResult.add(items);
        }
        base.put("审批结果", approvalResult);




        //跨域通办
        JSONObject SCOPERANGE = new JSONObject();
        JSONArray scoPes = basicInfo.getJSONArray("SCOPES");
        if (scoPes != null) {
            for (int i = 0; i < scoPes.size(); i++) {
                JSONObject jo = scoPes.getJSONObject(i);
                JSONArray DIVISIONS = jo.getJSONArray("DIVISIONS");
                SCOPERANGE.put("通办类型", jo.getString("SCOPERANGE_TEXT"));
                SCOPERANGE.put("通办形式", jo.getString("SCOPESHAPE_TEXT"));
                for (int j = 0; j < DIVISIONS.size(); j++) {
                    JSONObject jo1 = DIVISIONS.getJSONObject(j);
                    SCOPERANGE.put("通办区域", jo1.getString("DIVISION_FULL_NAME"));
                }
            }
        }
        base.put("跨域通办", SCOPERANGE);

        //特殊程序
        JSONObject tebiechengxu = new JSONObject();
        tebiechengxu.put("类型",
                isNotBlankOrNull(basicInfoex.getString("TSSC_TYPE_TEXT")) ? basicInfoex.getString("TSSC_TYPE_TEXT") : "无");
        tebiechengxu.put("总时限",
                isNotBlankOrNull(basicInfoex.getString("TSCXZSX")) ? basicInfoex.getString("TSCXZSX") : "无");
        tebiechengxu.put("总时限说明",
                isNotBlankOrNull(basicInfoex.getString("TSCXZSXSM")) ? basicInfoex.getString("TSCXZSXSM") : "无");
        tebiechengxu.put("特别程序说明",
                isNotBlankOrNull(basicInfoex.getString("SPECIAL_FLOW_NOTE")) ? basicInfoex.getString("SPECIAL_FLOW_NOTE") : "无");
        base.put("特别程序", tebiechengxu);
        return base;
    }

    public static JSONObject getScopesInfo(String html) {
        JSONObject scopes = new JSONObject();
        JSONObject response = JSONObject.parseObject(html);
        JSONObject data = response.getJSONObject("AUDIT_ITEM_EXTEND");
        JSONObject Range = new JSONObject();
        Range.put("服务对象", response.getJSONObject("AUDIT_ITEM").getString("SERVE_TYPE_TEXT"));
        Range.put("面向自然人事项主题分类",
                isNotBlankOrNull(data.getString("PERSON_THEME")) ? data.getString("PERSON_THEME") : "无");
        Range.put("面向自然人地方特色主题分类",
                isNotBlankOrNull(data.getString("PERSON_PLACE_THEME")) ? data.getString("PERSON_PLACE_THEME") : "无");
        Range.put("面向法人事项主题分类",
                isNotBlankOrNull(data.getString("LEGAL_THEME")) ? data.getString("LEGAL_THEME") : "无");
        Range.put("面向法人地方特色主题分类",
                isNotBlankOrNull(data.getString("LEGAL_PLACE_THEME")) ? data.getString("LEGAL_PLACE_THEME") : "无");
        Range.put("申请内容",
                isNotBlankOrNull(data.getString("SQNR")) ? data.getString("SQNR") : "无");
        scopes.put("受理范围", Range);
        scopes.put("受理条件", response.getJSONObject("AUDIT_ITEM").getString("ACCEPT_CONDITION"));
        return scopes;
    }

    public static JSONObject getHandlingProcedures(String html) {
        JSONObject handlingProcedures = new JSONObject();
        JSONObject response = JSONObject.parseObject(html);
        JSONArray WSBLLCT = response.getJSONObject("AUDIT_ITEM").getJSONArray("WSBLLCT");
        JSONArray CKBLLCT = response.getJSONObject("AUDIT_ITEM").getJSONArray("CKBLLCT");
        for (int i = 0; i < WSBLLCT.size(); i++) {
            JSONObject jo = WSBLLCT.getJSONObject(i);
            JSONObject onprocessingProcess = new JSONObject();
            String fileUrl = String.format("https:%s", jo.getString("FILEPATH"));
            onprocessingProcess.put("名称", jo.getString("ATTACHNAME"));
            onprocessingProcess.put("源地址", fileUrl);
            onprocessingProcess.put("minioId", fileDownloadAndUploadMinioGet(fileUrl, jo.getString("ATTACHNAME")));
            handlingProcedures.put("网上办理流程", onprocessingProcess);
        }
        for (int i = 0; i < CKBLLCT.size(); i++) {
            JSONObject processingProcess = new JSONObject();
            JSONObject jo1 = CKBLLCT.getJSONObject(i);
            String fileUrl1 = String.format("https:%s", jo1.getString("FILEPATH"));
            processingProcess.put("名称", jo1.getString("ATTACHNAME"));
            processingProcess.put("源地址", fileUrl1);
            processingProcess.put("minioId", fileDownloadAndUploadMinioGet(fileUrl1, jo1.getString("ATTACHNAME")));
            handlingProcedures.put("线下办理流程", processingProcess);
        }
        JSONArray data = response.getJSONArray("AUDIT_ITEM_FLOWSHEET");
        JSONArray Step = new JSONArray();
        for (int i = 0; i < data.size(); i++) {
            JSONObject jo2 = data.getJSONObject(i);
            JSONObject step = new JSONObject();
            step.put(jo2.getString("STEP_TEXT") + "," + "办理结果", jo2.getString("TRANSACT_RESULT"));
            step.put("审批标准", jo2.getString("CHECK_STANDARD"));
            step.put("送达方式", jo2.getString("TRANSPORT_TYPE"));
            step.put("时限", jo2.getString("TRANSACT_TIME_LIMIT"));
            step.put("审批人", jo2.getString("TRANSACTOR"));
            handlingProcedures.put("步骤", step);
            Step.add(step);
        }
        handlingProcedures.put("步骤", Step);
        return handlingProcedures;
    }

    public static List<JSONObject> getMaterialAll(String html) {
        JSONObject response = JSONObject.parseObject(html);

        //材料清单
        JSONArray data = response.getJSONArray("AUDIT_MATERIAL");

        List<JSONObject> material = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            JSONObject cailiaoqingdanItem = new JSONObject();
            JSONObject cailiaoqingdanItemOrg = data.getJSONObject(i);

            cailiaoqingdanItem.put("材料名称", cailiaoqingdanItemOrg.getString("MATERIAL_NAME"));
            cailiaoqingdanItem.put("材料形式",
                    cailiaoqingdanItemOrg.getString("ZZHDZB_TEXT") + ",原件：" +
                            cailiaoqingdanItemOrg.getString("PAGE_NUM") + ",复印件：" + cailiaoqingdanItemOrg.getString("PAGE_COPYNUM"));

            JSONObject qtyq = new JSONObject();
            qtyq.put("材料类型", cailiaoqingdanItemOrg.getString("MATERIAL_TYPE_TEXT"));
            qtyq.put("材料形式", cailiaoqingdanItemOrg.getString("ZZHDZB_TEXT"));
            qtyq.put("纸质材料规格", cailiaoqingdanItemOrg.getString("PAGE_FORMAT"));
            qtyq.put("是否免提交", isNotBlankOrNull(cailiaoqingdanItemOrg.getString("ISRELATELICENSE_TEXT")) ?
                    cailiaoqingdanItemOrg.getString("ISRELATELICENSE_TEXT") : "无");
            qtyq.put("要求", cailiaoqingdanItemOrg.getString("IS_NEED_TEXT"));
            cailiaoqingdanItem.put("材料要求", qtyq);


            JSONObject qtxx = new JSONObject();
            qtxx.put("来源渠道名称",
                    isNotBlankOrNull(cailiaoqingdanItemOrg.getString("SOURCE_TYPE_TEXT")) ?
                            cailiaoqingdanItemOrg.getString("SOURCE_TYPE_TEXT") : "无");
            qtxx.put("来源渠道说明",
                    isNotBlankOrNull(cailiaoqingdanItemOrg.getString("SOURCE_EXPLAIN")) ?
                            cailiaoqingdanItemOrg.getString("SOURCE_EXPLAIN") : "无");
            qtxx.put("填报须知",
                    isNotBlankOrNull(cailiaoqingdanItemOrg.getString("FILE_EXPLIAN")) ?
                            cailiaoqingdanItemOrg.getString("FILE_EXPLIAN") : "无");
            qtxx.put("备注信息",
                    isNotBlankOrNull(cailiaoqingdanItemOrg.getString("REMARK")) ?
                            cailiaoqingdanItemOrg.getString("REMARK") : "无");
            cailiaoqingdanItem.put("其他信息", qtxx);


            // 材料下载
            JSONObject material_download = new JSONObject();
            List<JSONObject> shiliyangbenList = new ArrayList<>();
            JSONArray downLoad = cailiaoqingdanItemOrg.getJSONArray("EXAMPLE_GUID");
            for (int k = 0; k < downLoad.size(); k++) {
                JSONObject down = downLoad.getJSONObject(k);
                JSONObject sample = new JSONObject();
                String downUrl = String.format("https:%s", down.getString("FILEPATH"));
                sample.put("名称", down.getString("ATTACHNAME"));
                sample.put("源地址", downUrl);
                sample.put("minioId", fileDownloadAndUploadMinioGet(downUrl, down.getString("ATTACHNAME")));
                shiliyangbenList.add(sample);
            }

            List<JSONObject> kongbaiyangbenList = new ArrayList<>();
            JSONArray Load1 = cailiaoqingdanItemOrg.getJSONArray("FORM_GUID");
            for (int z = 0; z < Load1.size(); z++) {
                JSONObject load = Load1.getJSONObject(z);
                JSONObject blank = new JSONObject();
                String downUrl1 = String.format("https:%s", load.getString("FILEPATH"));
                blank.put("名称", load.getString("ATTACHNAME"));
                blank.put("源地址", downUrl1);
                blank.put("minioId", fileDownloadAndUploadMinioGet(downUrl1, load.getString("ATTACHNAME")));
                kongbaiyangbenList.add(blank);
            }
            material_download.put("空白样本", kongbaiyangbenList);
            material_download.put("示例样本", shiliyangbenList);
            cailiaoqingdanItem.put("材料下载", material_download);


            // 中介服务 - medium_service
            List<JSONObject> zhongjiefuwuListOut = new ArrayList<>();
            JSONArray zhongjianfuwuListOrg = cailiaoqingdanItemOrg.getJSONArray("AGENTS");

            for (int c = 0; c < zhongjianfuwuListOrg.size(); c++) {
                JSONObject item = new JSONObject();
                JSONObject jo3 = zhongjianfuwuListOrg.getJSONObject(c);

                item.put("中介服务事项名称", jo3.getString("AGENT_SUBJECT_NAME"));
                item.put("中介服务事项编码", jo3.getString("AGENT_SUBJECT_CODE"));
                item.put("材料名称", cailiaoqingdanItemOrg.getString("MATERIAL_NAME"));
                String detailsUrl = String.format("http://zjcs.gdggzy.org.cn/gd-zjcs-pub/agentSubject/view-code/%s",
                        cailiaoqingdanItemOrg.getString("MATERIAL_NAME"));
                item.put("详情", detailsUrl);

                //中介服务-查看依据
                List<JSONObject> cainiaoyijvListOut = new ArrayList<>();
                JSONArray shedingyijvListOrg = jo3.getJSONArray("lAWS");
                for (int j = 0; j < shedingyijvListOrg.size(); j++) {
                    JSONObject jo1 = shedingyijvListOrg.getJSONObject(j);
                    JSONObject basis = new JSONObject();
                    basis.put("法律法规名称", jo1.getString("LAWNAME"));
                    basis.put("依据文号", jo1.getString("ACCORDINGNUMBER"));
                    basis.put("条款号", jo1.getString("TERMSNUMBER"));
                    basis.put("条款内容", jo1.getString("TERMSCONTENT"));
                    basis.put("颁布机构", jo1.getString("BFJG"));
                    cainiaoyijvListOut.add(basis);
                }
                item.put("设定依据", cainiaoyijvListOut);
                zhongjiefuwuListOut.add(item);
            }
            cailiaoqingdanItem.put("中介服务", zhongjiefuwuListOut);
            material.add(cailiaoqingdanItem);
        }

        return material;
    }

    public static JSONArray getCharge (String html){
        JSONObject response = JSONObject.parseObject(html);

        return response.getJSONArray("AUDIT_CHARGE");
    }

    public static JSONObject getOtherInfo (String html){
        JSONObject othInfo = new JSONObject();
        JSONObject res = new JSONObject();

        JSONObject response = JSONObject.parseObject(html);
        JSONObject data = response.getJSONObject("AUDIT_ITEM_EXTEND");
        JSONArray array = response.getJSONObject("AUDIT_ITEM").getJSONArray("LAW");
        res.put("申请人依法享有以下权利", data.getString("SQRQL"));
        res.put("申请人依法履行以下义务", data.getString("SQRYW"));

        othInfo.put("权利与义务", res);
        JSONArray arr = new JSONArray();
        for (int i = 0; i < array.size(); i++) {
            JSONObject jo = array.getJSONObject(i);
            JSONObject basis = new JSONObject();
            basis.put("法律法规名称", jo.getString("LAWNAME"));
            basis.put("依据文号", jo.getString("ACCORDINGNUMBER"));
            basis.put("条款号", jo.getString("TERMSNUMBER"));
            basis.put("颁布机关", jo.getString("BFJG"));
            basis.put("实施日期", jo.getString("SSRQ"));
            basis.put("条款内容", jo.getString("TERMSCONTENT"));
            arr.add(basis);
        }
        othInfo.put("设定依据", arr);
        JSONObject Legal = new JSONObject();
        JSONObject reconSideRation = new JSONObject();
        reconSideRation.put("部门", data.getString("XZFYBM"));
        reconSideRation.put("地址", data.getString("XZFYDZ"));
        reconSideRation.put("电话", data.getString("XZFYDH"));
        reconSideRation.put("网址",
                isNotBlankOrNull(data.getString("XZFYWZ")) ? data.getString("XZFYWZ") : "无");
        Legal.put("行政复议", reconSideRation);
        JSONObject litigation = new JSONObject();
        litigation.put("部门", data.getString("XZSSBM"));
        litigation.put("地址", data.getString("XZSSDZ"));
        litigation.put("电话", data.getString("XZSSDH"));
        litigation.put("网址",
                isNotBlankOrNull(data.getString("XZSSWZ")) ? data.getString("XZSSWZ") : "无");
        Legal.put("行政诉讼", litigation);
        othInfo.put("法律救济", Legal);
        return othInfo;
    }

    public static String fileDownloadAndUploadMinioGet (String url, String docName){
        // docName 文件名要带后缀
        try {
            JSONObject headers = new JSONObject();
            return DownloadAndUploadMinio.getInstance().downloadGet(
                    url,
                    headers,
                    new JSONObject(),
                    docName
            );
        } catch (Exception e) {
            e.printStackTrace();

        }
        return "";
    }

    /*******
     *  判断是否为null 或者 空字符串
     * @param str
     * @return
     */
    public static boolean isNotBlankOrNull (Object str){
        return str != null && !str.toString().equals("");
    }

}
